<template>
	<!-- 面包屑 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{path:'/welcome'}">首页</el-breadcrumb-item>
		<el-breadcrumb-item>用户管理</el-breadcrumb-item>
	</el-breadcrumb>
	<!-- 行内表单 -->
	<el-form :inline="true" :model="formInline" class="demo-form-inline">
		<el-form-item label="用户名">
			<el-input v-model="formInline.username" placeholder="请输入用户名" clearable @clear="query" />
		</el-form-item>
		<el-form-item label="手机号">
			<el-input v-model="formInline.mobile" placeholder="请输入手机号" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="seek">搜索</el-button>
			<el-button type="primary" @click="dialogVisible = true">新增用户</el-button>
			<el-button type="danger" @click="removeAll">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 新增权限弹出框 -->
	<el-dialog v-model="dialogVisible" :title="title" width="500" @close="cancle">
		<el-form :model="form" label-width="auto" style="max-width: 600px">
			<el-form-item label="用户名">
				<el-input v-model="form.username" placeholder="请输入用户名" />
			</el-form-item>
			<el-form-item label="手机号">
				<el-input v-model="form.mobile" placeholder="请输入手机号" />
			</el-form-item>
			<el-form-item label="昵称">
				<el-input v-model="form.nickname" placeholder="请输入昵称" />
			</el-form-item>
			<el-form-item label="邮箱">
				<el-input v-model="form.email" placeholder="请输入邮箱" />
			</el-form-item>
			<el-form-item label="密码">
				<el-input type="password" v-model="form.userpwd" />
			</el-form-item>
			<el-form-item label="状态">
			  <el-select v-model="form.del">
			    <el-option label="正常" :value="0" />  
			    <el-option label="停用" :value="1" />  
			  </el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false" @close="cancle">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 表格 -->
	<div>
		<el-table ref="multipleTableRef" border :data="tableData" row-key="id" style="width: 100%"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column property="id" label="id" />
			<el-table-column property="username" label="用户名" />
			<el-table-column property="mobile" label="手机号" />
			<el-table-column property="nickname" label="昵称" />
			<el-table-column property="email" label="邮箱" />
			<el-table-column label="状态">
				<template #default="scope">
					<el-tag type="primary" v-if="scope.row.del == 0">正常</el-tag>
					<el-tag type="danger" v-else>停用</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作">
				<template #default='scope'>
					<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>

	<!-- 分页 -->
	<el-pagination v-model:current-page="formInline.pageNum" v-model:page-size="formInline.pageSize"
		:page-sizes="[5, 10, 15, 20]" :size="size" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 8px;" />

</template>

<script lang="ts" setup>
	import { onMounted, reactive, ref } from 'vue'
	import type { TableInstance } from 'element-plus'
	import axios from 'axios'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import LoginVue from '../Login.vue'

	// 行内表单
	const formInline = reactive({
		id: '',
		username: '',
		userpwd: '',
		mobile: '',
		nickname: '',
		email: '',
		type: '',
		pageNum: 1,
		pageSize: 10,
		del:''// 与后端默认保持一致
	})
	
	// 表格数据相关
	const tableData = ref([]);
	const total = ref(0);
	const size = ref('default');
	const multipleTableRef = ref<TableInstance>()

	// 加载数据方法 - 统一调用分页接口
	const loadData = () => {
		axios.get(`http://localhost:8080/sysUser/findByPage`, {
			params: formInline
		})
			.then((resp) => {
				console.log("分页数据响应:", resp);
				if (resp.data.code === 200) {
					total.value = resp.data.data.total;  // 注意数据层级
					tableData.value = resp.data.data.list;
				} else {
					ElMessage.error('数据加载失败');
				}
			})
			.catch(error => {
				console.error('请求失败:', error);
				ElMessage.error('网络错误，请稍后重试');
			})
	}

	// 搜索功能
	const seek = () => {
		formInline.pageNum = 1;  // 搜索时重置到第一页
		loadData();
	}

	// 清空搜索条件
	const query = () => {
		formInline.username = '';
		formInline.mobile = '';
		formInline.pageNum = 1;
		loadData();
	}

	// 分页相关方法
	const handleSizeChange = (val) => {
		formInline.pageSize = val;
		loadData();
	}
	const handleCurrentChange = (val) => {
		formInline.pageNum = val;
		loadData();
	}

	// 页面加载时初始化数据
	onMounted(() => {
		loadData();
	})

	// 弹窗相关
	const dialogVisible = ref(false);
	const title = ref('新增用户');
	const form = ref({
		id: '',
		username: '',
		email: '',
		mobile: '',
		nickname: '',
		del: 1,
		userpwd: '123456',
	})

	// 新增用户方法
	const addUser = () => {
		axios.post('http://localhost:8080/sysUser/add', form.value)
			.then((resp) => {
				if (resp.data.code === 200) {
					ElMessage.success('新增成功');
					dialogVisible.value = false;
					loadData(); // 刷新数据
				} else {
					ElMessage.error('新增失败：' + (resp.data.message || '未知错误'));
				}
			})
			.catch(error => {
				console.error('新增请求失败：', error);
				ElMessage.error('网络错误，新增失败');
			})
	}

	// 编辑用户方法
	const editUser = () => {
		axios.put('http://localhost:8080/sysUser/edit', form.value)
			.then((resp) => {
				if (resp.data.code === 200) {
					ElMessage.success('编辑成功');
					dialogVisible.value = false;
					loadData(); // 刷新数据
				} else {
					ElMessage.error('编辑失败：' + (resp.data.message || '未知错误'));
				}
			})
			.catch(error => {
				console.error('编辑请求失败：', error);
				ElMessage.error('网络错误，编辑失败');
			})
	}

	// 统一提交方法
	const submitForm = () => {
		if (form.value.id) {
			editUser();
		} else {
			addUser();
		}
	}

	// 编辑功能
	const edit = (row) => {
		dialogVisible.value = true;
		title.value = '编辑用户';
		// 深拷贝避免直接修改表格数据
		form.value = { ...row };
	}

	// 取消操作
	const cancle = () => {
		form.value = {
			id: '',
			username: "",
			email: '',
			mobile: '',
			nickname: '',
			del: 1,
			userpwd: '123456',
		}
	}

	// 删除功能
	const remove = (id) => {
		ElMessageBox.confirm(
			'此操作将永久删除该数据, 是否继续?',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				axios.delete(`http://localhost:8080/sysUser/remove?id=${id}`)
					.then((resp) => {
						if (resp.data.code === 200) {
							ElMessage.success('删除成功');
							loadData(); // 重新加载数据
						} else {
							ElMessage.error('删除失败');
						}
					});
			})
			.catch(() => {
				ElMessage({ type: 'info', message: '取消删除' })
			})
	}

	// 批量删除
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => item.id)
	}
	const removeAll = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的数据');
			return;
		}
		
		ElMessageBox.confirm(
			`此操作将永久删除选中的${multipleSelection.value.length}条数据, 是否继续?`,
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				return axios.delete(`http://localhost:8080/sysUser/removeBatch`, {
					params: { ids: multipleSelection.value.join(',') }
				});
			})
			.then((resp) => {
				if (resp.data.code === 200) {
					ElMessage.success('批量删除成功');
					loadData(); // 重新加载数据
				} else {
					ElMessage.error('批量删除失败');
				}
			})
	}
</script>

<style>
	/* 面包屑样式 */
	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 15px;
		border-bottom: 1px solid #ddd;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}
</style>